<template>
    <el-table ref='tableRef' border :data='rowsData' class='w-100' @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="35" />
        <el-table-column align='center' prop='name' label='名称' />
        <el-table-column align='center' prop='code' label='编码' />
    </el-table>
</template>

<script lang="ts" setup>
    import { reactive, defineExpose, ref } from "vue"
    import { getRulesApi } from "../../../api/permissionRule"
    const tableRef = ref()
    const rowsData = reactive([])
    const selectedRows = new Set<any>()

    function handleSelectionChange(rows:any[]) {
        rowsData.forEach(row => {
            selectedRows.delete(row.id)
        })

        if(rows.length > 0) {
            rows.forEach(row => {
                selectedRows.add(row.id)
            })
        }
    }

    function getRules(menuId) {
        rowsData.splice(0)
        getRulesApi(menuId).then(rules => {
            if(rules.length > 0) {
                rules.forEach(row => {
                    rowsData.push(row)
                    if(selectedRows.has(row.id)) {
                        tableRef.value.toggleRowSelection(row)
                    }
                    
                })
                
            }

            
        })
    }

    function getValues() {
        return Array.from(selectedRows)
    }

    function setValues(values:any[]) {
        values.forEach(v => {
            selectedRows.add(v)
        })
        
    }

    defineExpose({
        getRules,
        getValues,
        setValues
    })
</script>